package me.jollyfly.jshop.user.server.controller;

import lombok.extern.slf4j.Slf4j;
import me.jollyfly.jshop.common.bean.ResultBean;
import me.jollyfly.jshop.user.client.api.UserApi;
import me.jollyfly.jshop.user.client.model.UserDO;
import me.jollyfly.jshop.user.client.model.dto.LoginUserDTO;
import me.jollyfly.jshop.user.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;


/**
 * created at 2018/1/9
 *
 * @author 354649
 */
@RestController
@Slf4j
public class UserDetailsController implements UserApi {

    @Autowired
    private UserService userService;

    @Override
    public ResultBean<LoginUserDTO> loadUserByUsername(String username) {
        UserDO userDO = userService.getByUsername(username);
        if (userDO == null) {
            return new ResultBean<>(null, ResultBean.Companion.getFAIL(), "用户名或密码错误");
        }
        LoginUserDTO userDTO = new LoginUserDTO();
        userDTO.setPassword(userDO.getPassword());
        userDTO.setRoles(userDO.getRoles());
        userDTO.setUsername(username);
        return new ResultBean<>(userDTO);
    }


    @Override
    public ResultBean<String> login(LoginUserDTO loginUserDTO) {
        log.debug("用户{}请求登录", loginUserDTO);
        UserDO userDO = new UserDO();
        userDO.setUsername(loginUserDTO.getUsername());
        userDO.setPassword(loginUserDTO.getPassword());
        return this.userService.login(userDO);
    }
}
